package lib.bone.system.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.lang.Validator;
import lib.bone.system.domain.entity.SysRole;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.*;

/**
 * @author: kindear
 * 获取用户角色标识 和 权限标识
 */

@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {
    /**
     * 加载用户服务
     */
    @Autowired
    SysUserService sysUserService;

    SysUser getLoginUser(Long loginId){
        Optional<SysUser> userOp = sysUserService.getById(loginId);
        //获取登录用户信息
        return userOp.orElse(null);
       // return userOp.get();
    }
    @Transactional
    @Override
    public List<String> getPermissionList(Object o, String s) {
        //List<String> permissions = new ArrayList<>();

        Set<String> permsSet = new HashSet<>();
        SysUser user = getLoginUser(Long.parseLong(o.toString()));
        if (Validator.isEmpty(user)){
            return new ArrayList<>(permsSet);
        }

        Set<SysRole> sysRoleSet = user.getRoles();
        for (SysRole sysRole:sysRoleSet){
//            roleIdList.add(sysRole.getId());
//            roleKeySet.add(sysRole.getRoleKey());
            List<String> perms = sysRole.getPermission();
            permsSet.addAll(perms);
        }
        //清理空值权限
        permsSet.remove("");
        return new ArrayList<>(permsSet);
    }

    @Override
    @Transactional
    public List<String> getRoleList(Object o, String s) {
        Set<String> rolesSet = new HashSet<>();
        SysUser user = getLoginUser(Long.parseLong(o.toString()));
        if (Validator.isEmpty(user)){
            return new ArrayList<>(rolesSet);
        }
        if (Validator.isNotEmpty(user.getRoles())){
            Set<SysRole> sysRoleSet = user.getRoles();
            for (SysRole sysRole:sysRoleSet){
                rolesSet.add(sysRole.getRoleKey());
            }
        }

        return new ArrayList<>(rolesSet);
    }
}
